package me.chyxion.blog.service.impl;

import java.util.List;
import me.chyxion.blog.model.User;
import me.chyxion.blog.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * Apr 19, 2018 17:01:26
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private JdbcTemplate jdbcTpl;

    /**
     * {@inheritDoc}
     */
    @Override
    public List<User> list() {
        return jdbcTpl.query("select * from blg_user",
            new BeanPropertyRowMapper<>(User.class));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public User find(int id) {
        return jdbcTpl.queryForObject(
            "select * from blg_user where id = ?",
            new BeanPropertyRowMapper<>(User.class), id);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void update(final User user) {
        jdbcTpl.update("update blg_user set name = ?, gender = ?, birth_date = ? where id = ?",
            user.getName(), user.getGender(), user.getBirthDate(), user.getId());
    }

    @Override
    public void delete(final int id) {
        jdbcTpl.update("delete from blg_user where id = ?", id);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void create(final User user) {
        jdbcTpl.update("insert into blg_user (name, gender, birth_date) values (?, ?, ?)",
            user.getName(), user.getGender(), user.getBirthDate());
    }
}
